package com.sunda.spmsorder.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.entity.OrderWorkshopDtl;
import com.sunda.spmsorder.mapper.MaterialSrmLongContractMapper;
import com.sunda.spmsorder.mapper.OrderLogMapper;
import com.sunda.spmsorder.mapper.OrderWorkshopDtlMapper;
import com.sunda.spmsorder.service.IOrderWorkshopDtlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 车间请购单详情表 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2021-02-02
 */
@Service
public class OrderWorkshopDtlServiceImpl extends ServiceImpl<OrderWorkshopDtlMapper, OrderWorkshopDtl> implements IOrderWorkshopDtlService {

    @Autowired
    OrderWorkshopDtlMapper orderWorkshopDtlMapper;

    @Autowired
    OrderLogMapper orderLogMapper;

    @Autowired
    MaterialSrmLongContractMapper materialSrmLongContractMapper;

    @Override
    public List<Map<String, Object>> getOrderWsDtl(String spmsWsId) {
        if (spmsWsId.trim().length() == 0){
            return null;
        }
        //List<OrderWorkshopDtl> orderWorkshopDtls = orderWorkshopDtlMapper.selectList(new QueryWrapper<OrderWorkshopDtl>().eq("SPMS_WS_ID", spmsWsId));
        List<Map<String, Object>> orderWorkshopDtls = orderWorkshopDtlMapper.getOrderWsDtlList(spmsWsId);
//        for(Map<String, Object> map : orderWorkshopDtls){
//            String materialNo = map.get("materialNo").toString();
//            map.put("materialSrmSourceList", materialSrmLongContractMapper.getByMaterialNo(materialNo));
//        }
        return orderWorkshopDtls;
    }

    /** 获取一个车间请购单明细信息，包含 在库库存、在途、安全库存等信息 */
    @Override
    public List<Map<String, Object>> getOrderWsDtlWithInventory(String spmsWsId) {
        if (spmsWsId.trim().length() == 0){
            return null;
        }
        List<Map<String, Object>> orderWorkshopDtls = orderWorkshopDtlMapper.getOrderWsDtlWithInventory(spmsWsId);
        return orderWorkshopDtls;
    }

    /**
     * 根据用户输入更新指定请购单详情信息——整体详情删除重建
     * {
     * 	"uuid": "13989b89217f40c09c89f67237c178df",
     * 	"spmsWsId": "GH011002-20210202-0001",
     * 	"userId": "20001",
     * 	"orderWorkshopDtl": [{
     * 		"rowId": 10,
     * 		"materialNo": "130011853",
     * 		"materialZhDesc": "马克杯 端底白瓷花13 普通包装 48PCS/CTN",
     * 		"materialEnDesc": "MUG",
     * 		"requestQty": 4,
     * 		"approvalQty": 4,
     * 		"basicUnit": "PCS",
     * 		"brand": "",
     * 		"rowStatus": "",
     * 		"rowComment": "",
     * 		"deviceId": "",
     * 		"deviceCategory": "",
     * 		"deviceType": "",
     * 		"materialCategory": "",
     * 		"longContractCode": ""
     *        }]
     * }
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateOrderWorkshopDtl(JSONObject doc) {
        try {
            String uuid = doc.getString("uuid");
            if (StringUtils.isEmpty(uuid) || !doc.containsKey("orderWorkshopDtl")){
                return ResponseResult.error("请求参数错误");
            }

            /** 删除车间请购单表中指定行项目 */
            orderWorkshopDtlMapper.delete(new QueryWrapper<OrderWorkshopDtl>().eq("uuid", uuid));

            /** 新建车间请购单行项目 */
            JSONArray array = doc.getJSONArray("orderWorkshopDtl");
            if (array.size() > 0){
                for (int i = 0; i < array.size(); i ++){
                    JSONObject obj = array.getJSONObject(i);
                    OrderWorkshopDtl owd = new OrderWorkshopDtl();
                    owd.setUuid(uuid);
                    owd.setRowId(Integer.parseInt(obj.getString("rowId")));
                    owd.setMaterialNo(obj.getString("materialNo"));
                    owd.setMaterialZhDesc(obj.getString("materialZhDesc"));
                    owd.setMaterialEnDesc(obj.getString("materialEnDesc"));
                    owd.setRequestQty(Double.parseDouble(obj.getString("requestQty")));
                    owd.setApprovalQty(Double.parseDouble(obj.getString("approvalQty")));
                    owd.setBasicUnit(obj.getString("basicUnit"));
                    owd.setBrand(obj.getString("brand"));
                    owd.setRowStatus(obj.getString("rowStatus"));
                    owd.setRowComment(obj.getString("rowComment"));
                    owd.setDeviceId(obj.getString("deviceId"));
                    owd.setDeviceCategory(obj.getString("deviceCategory"));
                    owd.setDeviceType(obj.getString("deviceType"));
                    owd.setMaterialCategory(obj.getString("materialCategory"));
                    owd.setLongContractCode(obj.getString("longContractCode"));

                    orderWorkshopDtlMapper.insert(owd);
                }
            }

            /** 添加请购单修改日志记录 */
            orderLogMapper.insertOrderLog(doc.getString("userId"),"更新车间请购单详情", uuid);

            return ResponseResult.success();
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @Override
    public List<OrderWorkshopDtl> getOrderWsDtls(JSONObject doc) {
        if (!doc.containsKey("spmsWsIds") || doc.getJSONArray("spmsWsIds").size() == 0){
            return null;
        }
        JSONArray array = doc.getJSONArray("spmsWsIds");
        List<String> spmsWsIds = array.toJavaList(String.class);
        return orderWorkshopDtlMapper.selectList(new QueryWrapper<OrderWorkshopDtl>().in("SPMS_WS_ID", spmsWsIds));
    }

    /** 获取多个车间请购单明细信息，包含 在库库存、在途库存、安全库存等信息； */
    @Override
    public List<Map<String, Object>> getOrderWsDtlList(JSONObject doc) {
        if (!doc.containsKey("spmsWsIds") || doc.getJSONArray("spmsWsIds").size() == 0){
            return null;
        }
        JSONArray array = doc.getJSONArray("spmsWsIds");
        List<String> spmsWsIds = array.toJavaList(String.class);
        return orderWorkshopDtlMapper.getOrderWorkshopDtlList(spmsWsIds);
    }
}
